import java.util.Arrays;

/*
*  选择排序
* */
public class selectSort {

    private static void sort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int mixIndex = i;
            int temp = arr[i];
            for (int j = i+1; j < arr.length; j++) {
                if (arr[j] < arr[mixIndex]) {
                    mixIndex = j;
                }
            }
//            arr[i] = arr[mixIndex];
//            arr[mixIndex] = temp;
            exchange(arr, i, mixIndex);
        }
    }

    static void sort2(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left+1; i <= right; i++) {
                if (arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
                if (arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
            }
            exchange(arr,minIndex, left);
            // 避免最大值就是数组开头，前面调换最小值会把最大值给换掉，所以要重新确定 maxIndex 的下标
            if (maxIndex == left) {
                maxIndex = minIndex;
            }
            exchange(arr, maxIndex, right);
            left++;
            right--;
        }
    }




    private static  void exchange(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {17,5,6,14,3,1,2};
        sort2(arr);
        System.out.println(Arrays.toString(arr));
    }

}
